//
//  YiHomeMenuCtrl.swift
//  yiplayer
//
//  Created by wkun on 2024/6/12.
//

import UIKit
import HXPhotoPicker
import AVKit
import MobileVLCKit

class YiHomeCtrl: BLVideoPlayer {
    
    let vlc_player = VLCMediaPlayer()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let bu = "https://www.baidu.com"
        let req = URLRequest(url: URL.init(string: bu)!)
        let se = URLSession.shared.dataTask(with: req)
        se.resume()
        
        self.nodataView.moreBtn.addTarget(self, action: #selector(handleMenuBtn), for: .touchUpInside)
        self.controlView.moreBtn.addTarget(self, action: #selector(handleMenuBtn), for: .touchUpInside)
        self.controlView.backBtn.addTarget(self, action: #selector(handleCloseVideo), for: .touchUpInside)
        
        weak var ws = self
        self.nodataView.onClick { v in
            ws?.handleMenuBtn()
        }
    }
    // MARK: - TouchEvents
    
    @objc func handleMenuBtn() {
        YiLeftMenuView.showLeftMenuView(self, width: self.view.frame.width, height: self.view.frame.height)
    }
    
    @objc func handleCloseVideo() {
        self.controlView.bgView.isHidden = true 
        self.stop()
        self.nodataView.isHidden = false
    }
    
    func handleMenuItem(index: Int) {
        let i = index
        if i == 0 {
            // 打开相册
            var config = PickerConfiguration.default
            config.previewView.bottomView.isHiddenEditButton = true
            config.selectOptions = [.video]
            config.selectMode = .single
            config.videoSelectionTapAction = .quickSelect
            
            Photo.picker(
                config
            ) { result, pickerController in
                // 选择完成的回调
                // result 选择结果
                //  .photoAssets 当前选择的数据
                //  .isOriginal 是否选中了原图
                // photoPickerController 对应的照片选择控制器
                
//                let images: [UIImage] = try await result.objects()
//                let urls: [URL] = try await result.objects()
                
//                print(urls)
                result.getURLs { urls in
                    print(urls)
                    if urls.count > 0 {
                        self.playVideo(url: urls.first!)
                    }
                }
            } cancel: { pickerController in
                // 取消的回调
                // photoPickerController 对应的照片选择控制器
            }
        }
        
        //文件
        else if i == 1 {
            self.openFile()
        }
        
        //网络
        else if i == 2 {
            print("开始搜索smb")
//            self.searchSmbServer()
            self.addListView(YiServerListView())
        }
    }
    
    // MARK: - 列表系统
    //展示的所有的子list
    var sublists = [UIView]()
    //类似于push
    func addListView(_ listView: UIView){
        listView.frame = self.view.bounds
        
        //隐藏前一个
        self.sublists.last?.isHidden = true
        
        self.sublists.append(listView)
        
        self.view.addSubview(listView)
    }
        
    //类似于pop
    func removeListView(){
        self.sublists.last?.removeFromSuperview()
        self.sublists.removeLast()
        
        //展示前一个
        self.sublists.last?.isHidden = false
    }
}

extension YiHomeCtrl{
    // MARK: - qi
    func playVideo(url: URL) {
        
        let fn = url.lastPathComponent
        let pl = self
        pl.stop()
        pl.play(withURL: url, videoTitle: fn)
    }
    
    func avplay(url: URL) {
        // 创建一个AVPlayer实例
        let player1 = AVPlayer(url: url)
         
        // 创建一个AVPlayerViewController实例并设置player
        let playerViewController = AVPlayerViewController()
        playerViewController.player = player1
         
        // 展示AVPlayerViewController
        self.present(playerViewController, animated: true) {
           playerViewController.player?.play() // 在视图控制器呈现后播放视频
        }
    }
    
    
    func play_vlc(path: String?) {
        if let path = path {
            vlc_player.drawable = self.view;
//            let media = VLCMedia.init(path: path)
            
            if let encodedUrlString = path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
                if let url = URL(string: encodedUrlString) {
                    let media = VLCMedia(url: url)
                    vlc_player.media = media
                    vlc_player.play()
                    return
                }
            }
            
            printLog("播放失败, url问题")
        }
    }
}


// MARK: - 导入系统文件App内的文件
extension YiHomeCtrl: UIDocumentPickerDelegate{
    ///调用系统api，打开FilePicker对话窗
    func openFile(){
        
        if #available(iOS 14.0, *) {
            
            //只打开视频
            if let ty = UTType("public.movie") {
                let controller = UIDocumentPickerViewController(forOpeningContentTypes: [ty])
                controller.shouldShowFileExtensions = true
                controller.delegate = self
                self.present(controller, animated: true)
            }
            
        } else {
            ///此处的字符串，可以查看iOS14中枚举注释中的UIT.
            ///如：
            /**
                An Adobe PDF document.
        
                **UTI:** com.adobe.pdf
        
                **conforms to:** public.data, public.composite-content

                public static var pdf: UTType { get }
            */
      
            let controller = UIDocumentPickerViewController(documentTypes: ["public.content"], in: .import)
            controller.delegate = self
            controller.allowsMultipleSelection = false
            self.present(controller, animated: true)
        }
    }
    
    // UIDocumentPickerDelegate methods
    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
        // 用户取消了文件选择
        print("取消文件选择")
    }

    ///实现UIDocumentPickerDelegate代理
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        ///读取文件之前需要先获取读取文件的授权
        if let url = urls.first{
            
            let isSecuredURL = url.startAccessingSecurityScopedResource()
            
            defer{
                ///释放权限.
                ///
                ///若需要鉴权，则停止鉴权，否则忽略
                if isSecuredURL {
//                    url.stopAccessingSecurityScopedResource()
                }
            }
            self.startMaunalRecory(ul: url)
        }
    }
    
    func startMaunalRecory(ul: URL) {
        
        self.playVideo(url: ul)
        
        ///拷贝文件到当前目录
//        if let toUrl = fileDir?.appendFilePathComponent(ul.lastPathComponent) {
//            do {
//                try FileManager.default.copyItem(at: ul, to: toUrl)
//                self.loadFileData()
//            } catch {
//
//            }
//        }
    }
}


//smb访问
extension YiHomeCtrl {
    
//    [[SMBDiscovery sharedInstance] stopDiscovery];
    
    func searchSmbServer() {
//        SMBDiscovery.sharedInstance()?.start(of: .any, added: { smbDevice in
//            print("Device added: %@", smbDevice);
//        }, removed: { smbDevice in
//            print("Device added: %@", smbDevice);
//        })
    }
}
